package com.simon.annual.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.simon.annual.entity.ReportIncomeanalysi;
import com.simon.annual.entity.ReportIncomestructure;
import com.simon.annual.entity.ReportNeeq;
import com.simon.annual.entity.ReportPartner;
import com.simon.annual.repositoy.IReportIncomeanalysiRepositoy;
import com.simon.annual.repositoy.IReportIncomestructureRepositoy;
import com.simon.annual.repositoy.IReportNeeqRepositoy;
import com.simon.annual.repositoy.IReportPartnerRepositoy;
import com.simon.annual.service.IAbortManager;
import com.simon.annual.service.ICompanyPublicInfo;

/**
 * 第四节:管理层讨论与分析
 * */
@Service
public class FindAbortManagerImpl implements IAbortManager {

	@Resource
	private ICompanyPublicInfo companyPublicInfo;
	@Resource
	private IReportPartnerRepositoy reportPartnerRepositoy;
	@Resource
	private IReportIncomeanalysiRepositoy reportIncomeanalysiRepositoy;
	@Resource
	private IReportIncomestructureRepositoy reportIncomestructureRepositoy;
	@Resource
	private Environment env;
	@Resource
	private IReportNeeqRepositoy reportNeeqRepositoy;
	
	
	@Override
	public ReportNeeq analysis(Document doc, ReportNeeq reportNeeq, int companyPtrId) {
		Elements na= doc.getElementsMatchingText(env.getProperty("pdf.four"));
		Element four = na.last();
		if(four!=null){
			for (Element element : na) {
				if(element.tagName().startsWith("h")&&element.tagName().length()==2){
					four= element;
					break;
				}
			}
			//商业模式
			Element busi = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.changed"), four.nextElementSibling(), "",0);
			reportNeeq.setBusinessModel(busi.text());
			//年度内变化统计
			Element changes = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.changed"),four.nextElementSibling(), -80);
			changes = companyPublicInfo.getNextTag(changes, changes);
			int de =0;
			Elements trss = changes.select("table tr");
			for (int i = 0; i < trss.size(); i++) {
				if(trss.get(i).getElementsMatchingOwnText(env.getProperty("pdf.four.changed.no")).hasText()){
					de=2;
				}
				for (Element ell : trss.get(i).children()) {
					if(!ell.hasText()){
						ell.remove();
					}
				}
			}
			Elements tds = changes.select("table tr > *");
			if(tds.size()==16||tds.size()==18){
				reportNeeq.setIndustryChanged(tds.get(1+de).text());
				reportNeeq.setMainBusinessChanged(tds.get(3+de).text());
				reportNeeq.setMainProductChanged(tds.get(5+de).text());
				reportNeeq.setClientTypeChanged(tds.get(7+de).text());
				reportNeeq.setKeyResourceChanged(tds.get(9+de).text());
				reportNeeq.setSalesChannelChanged(tds.get(11+de).text());
				reportNeeq.setIncomeSourceChanged(tds.get(13+de).text());
				reportNeeq.setBusinessModelChanged(tds.get(15+de).text());
			}
			//报告期内经营情况回顾
			Element performance = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.performance"), changes, -150);
			Element performance_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.sy"), performance, "",0);
			reportNeeq.setPerformanceReview(performance_.text());
			//主营业务分析
			Element mainElement = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.sy"), changes, -30);
			//项目重大变动原因
			Element sca = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.sca"), mainElement, -15);
			Element scaText = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.income"), sca, "",0);
			reportNeeq.setPl_SCA(scaText==null?"":scaText.text());
			//收入构成
			Element incomeStructure = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.income.amt"), mainElement, -35);
			List<ReportIncomestructure> incomestructureList = new ArrayList<ReportIncomestructure>();
			Elements  intrs = incomeStructure.select("table tr");
			for (int i = 1; i < intrs.size()-1; i++) {
					ReportIncomestructure incomestructure = new ReportIncomestructure();
					Elements intds = intrs.get(i).children();
					if(intds.size()!=5){break;}
					incomestructure.setName(intds.get(0).text());
					incomestructure.setRevenueThisPeriod(intds.get(1).text());
					incomestructure.setCostThisPeriod(intds.get(2).text());
					incomestructure.setRevenueLastPeriod(intds.get(3).text());
					incomestructure.setCostLastPeriod(intds.get(4).text());
					incomestructure.setProjectScopeId(companyPtrId);
					incomestructureList.add(incomestructure);
			}
			reportIncomestructureRepositoy.save(incomestructureList);
			//按产品分类分析
			Element incomeAnalysis = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.analysis"), incomeStructure, 2);
			if(incomeAnalysis!=null){
				Element incomeAnalysis_  = companyPublicInfo.findNextTag("table",incomeAnalysis);
				List<ReportIncomeanalysi> reportIncomeanalysiList = new ArrayList<ReportIncomeanalysi>();
				Elements  inctrs = incomeAnalysis_.select("table tr");
				for (int i = 1; i < inctrs.size(); i++) {
					ReportIncomeanalysi reportIncomeanalysi =new ReportIncomeanalysi();
					Elements inctds = inctrs.get(i).children();
					if(inctds.size()!=5){break;}
					reportIncomeanalysi.setName(inctds.get(0).text());
					reportIncomeanalysi.setRevenueThisPeriod(inctds.get(1).text());
					reportIncomeanalysi.setPctThisPeriod(inctds.get(2).text());
					reportIncomeanalysi.setRevenueLastPeriod(inctds.get(3).text());
					reportIncomeanalysi.setPctLastPeriod(inctds.get(4).text());
					reportIncomeanalysi.setProjectScopeId(companyPtrId);
					reportIncomeanalysiList.add(reportIncomeanalysi);
				}
				//按区域分类分析
				Element incomeAnalysis_a = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.analysis.a"), incomeAnalysis.nextElementSibling(), 2);
				if(incomeAnalysis_a!=null){
					incomeAnalysis =companyPublicInfo.findNextTag("table",incomeAnalysis_a);
					Elements  irs = incomeAnalysis.select("table tr");
					for (int i = 1; i < irs.size(); i++) {
						ReportIncomeanalysi reportIncomeanalysi =new ReportIncomeanalysi();
						Elements inctds = irs.get(i).children();
						reportIncomeanalysi.setName(inctds.get(0).text());
						reportIncomeanalysi.setRevenueThisPeriod(inctds.get(1).text());
						reportIncomeanalysi.setPctThisPeriod(inctds.get(2).text());
						reportIncomeanalysi.setRevenueLastPeriod(inctds.get(3).text());
						reportIncomeanalysi.setPctLastPeriod(inctds.get(4).text());
						reportIncomeanalysi.setProjectScopeId(companyPtrId);
						reportIncomeanalysiList.add(reportIncomeanalysi);
					}
				}
				reportIncomeanalysiRepositoy.save(reportIncomeanalysiList);
			}
			//收入构成变动的原因
			Element income_SCA = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.incomeSCA"), incomeStructure.nextElementSibling(), -8);
			if(income_SCA!=null){
				Element income_SCA_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.sfSCA"),income_SCA, "",0);
				reportNeeq.setIncome_SCA(income_SCA_.text());
			}
			//现金流量状况
			Element cf_SCA = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.sfSCA"), incomeStructure, -25);
			//现金流量分析
			Element cf_SCA_ay = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.sfSCA.ay"), cf_SCA, -10);
			if(cf_SCA_ay!=null){
				Element cf_SCA_ay_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.client"), cf_SCA_ay, "",0);
				reportNeeq.setCf_SCA(cf_SCA_ay_.text());
			}
			//主要客户情况 
			List<ReportPartner> reportPartnerList = new ArrayList<ReportPartner>();
			Element clients = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.client.name"), cf_SCA, -10);
			if(clients!=null){
				clients = companyPublicInfo.getNextTag(clients, clients);
				Elements cliente =  clients.select("tr");
				for (int i = 1; i < cliente.size()-1; i++) {
					ReportPartner reportPartner =new ReportPartner();
					Elements ctds = cliente.get(i).children();
					if(cliente.get(i).getElementsMatchingText(env.getProperty("pdf.four.main.name")).hasText()|| ctds.size()!=5){
						break;
					}
					reportPartner.setName(ctds.get(1).text());
					reportPartner.setTransactionValue(ctds.get(2).text());
					reportPartner.setTransactionPct(ctds.get(3).text());
					reportPartner.setIsAffiliated(ctds.get(4).text());
					reportPartner.setProjectScopeId(companyPtrId);
					reportPartner.setType("C");
					reportPartnerList.add(reportPartner);
				}
			}
			//主要供应商情况 
			Element main = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.main.name"), cf_SCA, -15);
			if(main!=null){
				if(main.childNodeSize()==1){
					main= companyPublicInfo.findNextTag("table", main);
				}else{
					main = companyPublicInfo.getNextTag(main,main);
				}
				Elements mains =  main.select("tr");
				//处理三段黏连
				de =0;
				for (int i = 1; i < mains.size(); i++) {
					if(mains.get(i).getElementsMatchingText(env.getProperty("pdf.four.main.name")).hasText()){
						de=i;
						break;
					}
				}
				for (int i = de+1; i < mains.size()-1; i++) {
					ReportPartner reportPartner =new ReportPartner();
					Elements ctds = mains.get(i).children();
					if(mains.get(i).getElementsMatchingText(env.getProperty("pdf.four.dev.amt")).hasText()|| ctds.size()!=5){
						break;
					}
					reportPartner.setName(ctds.get(1).text());
					reportPartner.setTransactionValue(ctds.get(2).text());
					reportPartner.setTransactionPct(ctds.get(3).text());
					reportPartner.setIsAffiliated(ctds.get(4).text());
					reportPartner.setProjectScopeId(companyPtrId);
					reportPartner.setType("S");
					reportPartnerList.add(reportPartner);
				}
			}
			reportPartnerRepositoy.save(reportPartnerList);
			//研发支出与专利
			Element rnd = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.dev.amt"), cf_SCA, -40);
			if(rnd!=null){
	//			rnd = companyPublicInfo.getNextTag(rnd,rnd);
	//			rnd = companyPublicInfo.findNextTag("table", rnd);
				Elements rnds = rnd.select("table tr");
				if(rnds.size()>1){
					de=0;
					for (int i = 1; i < rnds.size(); i++) {
						if(rnds.get(i).getElementsMatchingText(env.getProperty("pdf.four.dev.amt")).hasText()){
							de=i-1;
							break;
						}
					}
					reportNeeq.setRndThisPeriod(rnds.get(de+1).children().get(1).text());
					reportNeeq.setRndLastPeriod(rnds.get(de+1).children().get(2).text());
					if(rnds.size()>2){
					reportNeeq.setRndPctThisPeriod(rnds.get(de+2).children().get(1).text());
					reportNeeq.setRndPctLastPeriod(rnds.get(de+2).children().get(2).text());
					}
				}
			}
			//专利情况
			Element patentQty = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.patent"), cf_SCA, -60);
			if(patentQty!=null){
				Elements qtyTds = patentQty.select("tr > *");
				if(qtyTds.size()==4){
					reportNeeq.setPatentQty(qtyTds.get(1).text());
					reportNeeq.setInventionPatentQty(qtyTds.get(3).text());
				}else{
					reportNeeq.setPatentQty(qtyTds.get(3).text());
					reportNeeq.setInventionPatentQty(qtyTds.get(5).text());
				}
			}
			//研发情况
			Element rndReview  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.rnd"), cf_SCA, -70);
			if(rndReview!=null){
				Element bs = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.bs"), rndReview, "",0);
				reportNeeq.setRndReview(bs.text());
			}
			//资产负债项目重大变动原因
			Element bs_SCA_  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.bsSCA"), cf_SCA, -30);
			if(bs_SCA_!=null){
				cf_SCA = bs_SCA_;
				Element bs = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.associated"), bs_SCA_, "",0);
				reportNeeq.setBs_SCA(bs.text());
			}
			//主要控股子公司、参股公司情况
			Element subsidiary  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.subsidiary"), cf_SCA, -15);
			if(subsidiary!=null){
				cf_SCA=subsidiary;
				Element subsidiary_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.derivatives"), subsidiary, "",0);
				reportNeeq.setMajorSubsidiaryOrAssociatedReview(subsidiary_.text());
			}
			//委托理财及衍生品投资情况
			Element entrusted  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.derivatives"), cf_SCA, -50);
			if(entrusted!=null){
				cf_SCA=entrusted;
				Element entrusted_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.exterior"), entrusted, "",0);
				reportNeeq.setEntrustedOrDerivativesReview(entrusted_.text());
			}
			//外部环境的分析
			Element exterior  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.exterior"), cf_SCA, -125);
			Element exterior_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.competition"), exterior, "",0);
			reportNeeq.setExteriorEnvAnalysis(exterior_.text());
			//竞争优势分析
			Element competition  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.competition"), exterior, -120);
			Element competition_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.going"), competition, "",0);
			reportNeeq.setCompetitionAdvantagesAnalysis(competition_.text());
			//持续经营评价
			Element going  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.going"), competition, -55);
			Element going_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.fu"), going, "",0);
			reportNeeq.setGoingConcernAnalysis(going_.text());
			//扶贫与社会责任
	//		Element social = xml.findNextTag("table", going);
	//		social = xml.getNextTag(social,social);
	//		reportNeeq.setSocialResponsibilityReview(social.text());
			//自愿披露
			Element voluntary  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.voluntary"), going, -35);
			if(voluntary!=null){
				Element voluntary_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.fu"), voluntary, "",0);
				reportNeeq.setVoluntaryDisclosure(voluntary_.text());
			}
			Element goings  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.fu.z"), going, -5);
			if(goings!=null){
				//未来展望(自愿披露)
				//行业发展趋势
				Element uncertainty  = companyPublicInfo.findNextByCharEndChar(env.getProperty("pdf.four.uncertainty_"),env.getProperty("pdf.four.risk.b"), goings, -30);
				if(uncertainty!=null){
					Element uncertainty_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.development.b"), uncertainty, "",0);
					reportNeeq.setIndustryTrends(uncertainty_.text());
				}
				//公司发展战略
				Element development  = companyPublicInfo.findNextByCharEndChar(env.getProperty("pdf.four.development"),env.getProperty("pdf.four.risk.b"), goings, -50);
				if(development!=null){
					Element development_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.business.b"), development, "",0);
					reportNeeq.setDevelopmentStrategy(development_.text());
				}
				//经营计划或目标
				Element business  = companyPublicInfo.findNextByCharEndChar(env.getProperty("pdf.four.business"),env.getProperty("pdf.four.risk.b"), goings, -60);
				if(business!=null){
					Element business_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.uncertainty.b"), business, "",0);
					reportNeeq.setBusinessPlan(business_.text());
				}
				//不确定性因素
				goings  = companyPublicInfo.findNextByCharEndChar(env.getProperty("pdf.four.uncertainty"),env.getProperty("pdf.four.risk.b"), goings, -70);
				if(goings!=null){
					Element uncertaint_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.risk.b"), goings, "",0);
					reportNeeq.setBusinessPlan(uncertaint_.text());
				}
			}
			//三、风险因素
			//持续到本年度的风险因素
			Element risk  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.risk.b"), going, -260);
			Element risk_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.risk.new"), risk, "",0);
			reportNeeq.setRiskLasted(risk_.text());
			//报告期内新增的风险因素
			Element riskNew  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.risk.new"), risk, -20);
			if(riskNew!=null){
				Element riskNew_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.four.board"), riskNew, "",0);
				reportNeeq.setRiskNew(riskNew_.text());
			}
			//非标准审计意见说明
			Element mao  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.board"), risk, -10);
			if(mao!=null){
				mao = companyPublicInfo.findNextTag("table",mao);
				Elements maotr = mao.select("table tr");
				reportNeeq.setIs_MAO(maotr.get(0).child(1).text());
				reportNeeq.setAuditOpinion(maotr.get(1).child(1).text());
				reportNeeq.setBoard_statement_on_MAO(maotr.last().text());
			}
			//关键事项审计说明
			Element statement  = companyPublicInfo.findNextByChar(env.getProperty("pdf.four.mana"), risk, -5);
			if(statement!=null){
				Element statement_ = companyPublicInfo.findEndByChar(env.getProperty("pdf.five"), riskNew, "",0);
				reportNeeq.setStatement_on_KIAO(statement_.text()); 
			}
			return reportNeeqRepositoy.save(reportNeeq);
		}
		return reportNeeq;
	}

}
